package com.kandroid.chatclient;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

/**
 * Created by kz on 02/11/2017.
 */

public class SettingActivity extends AppCompatActivity
        implements View.OnClickListener {
    public static final int CHOOSE_PHOTO = 1001;

    private ImageView avatarIv;
    private TextView saveTv;
    private String imagePath;
    private SharedPreferences sharedPreferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        getSupportActionBar().hide();

        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        imagePath = sharedPreferences.getString("avatar", "");

        initViews();
    }

    private void initViews() {
        avatarIv = findViewById(R.id.iv_avatar);
        saveTv = findViewById(R.id.tv_save);

        avatarIv.setOnClickListener(this);
        saveTv.setOnClickListener(this);

        Bitmap bm = BitmapFactory.decodeFile(imagePath);
        if(bm != null) {
            avatarIv.setImageBitmap(bm);
        }
    }

    public static void jumpToActivity(Context context) {
        Intent intent = new Intent(context, SettingActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_avatar:
                pickPicture();
                break;
            case R.id.tv_save:
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("avatar", imagePath);
                edit.commit();

                finish();
                break;
        }
    }

    private void pickPicture() {
        //同样new一个file用于存放照片
        File imageFile = new File(Environment.getExternalStorageDirectory(), "outputImage.jpg");
        if (imageFile.exists()) {
            imageFile.delete();
        }
        try {
            imageFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //转换成Uri
        Uri imageUri = Uri.fromFile(imageFile);
        //开启选择呢绒界面
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        //设置可以缩放
        intent.putExtra("scale", true);
        //设置可以裁剪
        intent.putExtra("crop", true);
        intent.setType("image/*");
        //设置输出位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //开始选择
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CHOOSE_PHOTO && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            imagePath = getImagePath(uri, null);
            if (imagePath != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                avatarIv.setImageBitmap(bitmap);
            } else {
                Toast.makeText(this, "图片读取失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null,
                null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
}
